const http = require('../../utils/util')
const Base64 = require('../../utils/base')
const app = getApp()
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		bottom: 0,
		tabbarHeight: 0, //tabbar高度
		showTopUp: false, //自定义充值面板显示隐藏
		type: 0, //类型 0全部
		store_id: null, //店铺id


		navBarList: ['全部', '次卡', '期卡', '小时卡', '储值卡'],
		navTabIndex: 0,

		step: 0, //每一步的长度
		x: -19, //小圆点位置
		stepIndex: 0, //当前第几步骤
		cardIndex: -1, //当前点击的卡片

		cardList: [], //卡片数据
		shopList: [], //商铺数据
		shopIndex: 0,
		isPaying:true, //是否正在支付?
		page:1, //分页
		isNext:true, //是否有下一页
		money:'', //自定义充值金额
		isBack:false,
		empty:false
	},

	// 导航栏切换
	navBarIndex: function(e) {
		this.setData({
			navTabIndex: e.currentTarget.dataset.index,
			type: e.currentTarget.dataset.index,
			cardIndex: -1, //切换导航时清空状态
			stepIndex: 0,
			x: -19,
			page:1,
			isNext:true,
			cardList:[],
			cardIndex: -1,
			empty:false
		},()=>{
			// 修改type值 获取卡片数据
			this.getCardList()
		})
		

	},
	//点击天数
	dayTap(e) {
		this.circleHandler(e)
	},
	// 点击步骤条移动小圆点位置
	circleHandler(e) {
		//判断几个步骤
		let step_num=e.currentTarget.dataset.item.set_day.length
		//用户点击的x轴坐标
		let userX = e.detail.x
		if(step_num==4){
			if (20 < userX && userX < 120) {
				this.setData({
					x: -19,
					stepIndex: 0
				})
			} else if (120 < userX && userX < 180) {
				this.setData({
					x: 170,
					stepIndex: 1
				})
			} else if (180 < userX && userX < 270) {
				this.setData({
					x: 359,
					stepIndex: 2
				})
			} else if (270 < userX) {
				this.setData({
					x: 548,
					stepIndex: 3
				})
			}
		}else if(step_num==3){
			if (20 < userX && userX < 120) {
				this.setData({
					x: -19,
					stepIndex: 0
				})
			} else if (120 < userX && userX < 260) {
				this.setData({
					x: 270,
					stepIndex: 1
				})
			} else if (260 < userX) {
				this.setData({
					x: 548,
					stepIndex: 2
				})
			}
		}else if(step_num==2){
			if (20 < userX && userX < 270) {
				this.setData({
					x: -19,
					stepIndex: 0
				})
			} else if (270 < userX) {
				this.setData({
					x: 548,
					stepIndex: 1
				})
			}
		}
	},
	//卡片点击事件
	cardHandler(e) {
		if (this.data.cardIndex !== e.currentTarget.dataset.cardindex) {
			this.setData({
				cardIndex: e.currentTarget.dataset.cardindex,
				stepIndex: 0,
				x: -19
			})
		}else{
			this.setData({
				cardIndex: -1,
				stepIndex: 0,
				x: -19
			})
		}
	},
	//点击购买
	purchase(e) {
		let _this=this
		let user_token = wx.getStorageSync('user_token')
		if (!user_token) {
			wx.showModal({
				title: '提示',
				content: '你还没有登陆，是否登录?',
				success(res) {
					if (res.confirm) {
						wx.clearStorageSync()
						_this.login()
					}
				}
			})
			return
		}
		let {type,title,id} =e.currentTarget.dataset.cardinfo
		if(!this.data.isPaying) return 
		if (type == 1 ) { //购买(次卡,期卡)
			let {price,day}=e.currentTarget.dataset.cardinfo.set_day[this.data.stepIndex]
			this.wxPayment(id,type,price,day)
		} else if (type == 2 || type == 3) { // (小时卡)
			let {cost,hour} = e.currentTarget.dataset.cardinfo
			this.wxPayment(id,type,cost,hour)
		} else if (type == 4) { //充值
			let {price,day} = e.currentTarget.dataset.cardinfo
			wx.showModal({
				title: title,
				content: '充值完成后无法退款 如遇特殊问题请联系客服处理',
				success(res) {
					if(res.confirm){
						_this.wxPayment(id,type,price,day)
					}
				}
			})
		}
	},
	// 微信支付
	wxPayment(id,type,price,day) {
		let _this=this
		this.setData({
			isPaying:false
		})
		let data = {
			user_id: wx.getStorageSync('user_id'),
			user_token: wx.getStorageSync('user_token'),
			id:id,
			store_id: this.data.store_id,
			type: type,
			price:price,
			day:day
		}
		http.post('user/info', Base64.encode(JSON.stringify(data))).then((res) => {
			if (res.status == 1) {
				let data=res.result
				wx.requestPayment({
				  timeStamp: data.timeStamp,
				  nonceStr: data.nonceStr,
				  package: data.package,
				  signType: data.signType,
				  paySign: data.paySign,
				  success:(res)=>{
					  wx.showToast({
					  	title:'支付成功',
					  	icon:'none',
						duration:1000
					  })
					  setTimeout(()=>{
					  	if(app.globalData.isFrom1){
					  		app.globalData.isFrom1=false
							app.globalData.isFrom2=true
					  		wx.navigateTo({
					  			url:'/pages/index/store/store?id='+app.globalData.seat_params.store_id
					  		})
					  	}else{
							wx.switchTab({
								url:'/pages/mine/mine'
							})
						}
					  },1000)
				  },
				  fail:()=>{
					  wx.showToast({
						  title:'支付失败',
						  icon:'none'
					  })
				  },
				  complete:()=>{
					 _this.setData({
					 	isPaying:true
					 }) 
				  }
				})
			}else{
				_this.setData({
					isPaying:true
				}) 
				wx.showToast({
					title:res.message,
					icon:'none'
				})
			}
		})
	},
	//上拉触底
	onReachBottom(){
		if(this.data.isNext){
			this.setData({
				isNext:false,
				page:++this.data.page
			},()=>{
				this.getCardList()
			})
		}
	},
	//获取卡片数据
	getCardList() {
		let data = {
			store_id:this.data.store_id,
			type: this.data.type,
			page:this.data.page
		}
		http.post('recharge/reInfo', Base64.encode(JSON.stringify(data))).then((res) => {
			wx.hideLoading()
			if (res.status == 1) {
				if(res.result.length==0 && this.data.page==1){
					this.setData({
						empty:true
					})
				}
				if(res.result.length!==0){
					this.setData({
						isNext:true
					})
					app.globalData.store_id=null
					app.globalData.type_c=0
				}
				this.setData({
					cardList: JSON.parse(JSON.stringify([...this.data.cardList,...res.result])) 
				})
			}
		})
	},
	async getShopList() {
		let res=await http.post('ranking/store')
		if(res.status==1){ 
			let index= res.result.findIndex(v=>v.id==this.data.store_id)
			this.setData({
				shopList: res.result,
				store_id: this.data.store_id?this.data.store_id:res.result[0].id,
				page:1,
				isNext:true,
				cardList:[],
				cardIndex:-1,
				shopIndex:index==-1?0:index
			}, () => {
				//获取卡片数据
				this.getCardList()
			})
		}else {
			wx.showToast({
				title: res.message,
				icon: 'none'
			})
		}
	},
	//选择门店
	changeShop(e) {
		if (this.data.shopIndex == e.detail.value) return
		let id = this.data.shopList[e.detail.value].id
		this.setData({
			shopIndex: e.detail.value,
			store_id: id,
			page:1,
			isNext:true,
			cardList:[],
			cardIndex:-1,
			empty:false
		})
		//重新获取卡片数据
		this.getCardList()
	},
	//点击自定义充值按钮，显示
	customTopUp() {
		this.setData({
			showTopUp: true
		})
	},
	//自定义充值支付
	customTopUpPay(){
		let _this=this
		if(this.data.money<10){
			return wx.showToast({
				title:'充值金额不能低于10元',
				icon:'none'
			})
		}
		if(!this.data.isPaying) return
		this.setData({
			isPaying:false
		})
		let data = {
			user_id: wx.getStorageSync('user_id'),
			user_token: wx.getStorageSync('user_token'),
			type: 5,
			price:this.data.money,
			store_id:this.data.store_id
		}
		http.post('user/info', Base64.encode(JSON.stringify(data))).then((res) => {
			if (res.status == 1) {
				let data=res.result
				wx.requestPayment({
				  timeStamp: data.timeStamp,
				  nonceStr: data.nonceStr,
				  package: data.package,
				  signType: data.signType,
				  paySign: data.paySign,
				  success:(res)=>{
					  return
					  _this.setData({
					  	showTopUp: false
					  })
					  wx.showToast({
					  	title:'支付成功',
					  	icon:'none',
						duration:1000
					  })
					  setTimeout(()=>{
					  	if(app.globalData.isFrom1){
					  		app.globalData.isFrom1=false
					  		app.globalData.isFrom2=true
					  		wx.navigateTo({
					  			url:'/pages/index/store/store?id='+app.globalData.seat_params.store_id
					  		})
					  	}else{
							wx.switchTab({
								url:'/pages/mine/mine'
							})
						}
					  },1000)
				  },
				  fail:()=>{
					  wx.showToast({
						  title:'支付失败',
						  icon:'none'
					  })
				  },
				  complete:()=>{
					 _this.setData({
					 	isPaying:true
					 }) 
				  }
				})
			}else{
				_this.setData({
					isPaying:true
				}) 
				wx.showToast({
					title:res.message,
					icon:'none'
				})
			}
		})
	},
	//隐藏自定义充值面板
	hideTopUp() {
		this.setData({
			showTopUp: false
		})
	},
	//输入框聚焦时
	inputFours(e) {
		this.setData({
			bottom: e.detail.height
		})
	},
	//获取tabbar高度
	getTabbarHeight() {
		try {
			const res = wx.getSystemInfoSync()
			//获取tabbar高度
			const tabbarHeight = (res.screenHeight - res.windowHeight - res.statusBarHeight) * res.pixelRatio
			this.setData({
				tabbarHeight: tabbarHeight * 3
			})
		} catch (e) {
			// Do something when catch error
		}
	},
	//返回提交订单页面
	goBack(){
		if(app.globalData.isFrom1){
			app.globalData.isFrom1=false
			app.globalData.isFrom2=true
			wx.navigateTo({
				url:'/pages/index/store/store?id='+app.globalData.seat_params.store_id
			})
		}
	},
	//登录
	login() {
		wx.login({
			success(res) {
				if (res.code) {
					wx.setStorageSync('code', res.code)
				} else {}
			}
		})
		const _this = this
		wx.getUserProfile({
			desc: '获取用户相关信息',
			success: function(obj) {
				let code = wx.getStorageSync('code')
				var data = {
					code: code,
					encryptedData: obj.encryptedData,
					iv: obj.iv,
				}
				http.post('wechat/login', Base64.encode(JSON.stringify(data))).then(res => {
					if (res.status != 1) {}
					wx.setStorageSync('user_id', res.result.user_id)
					wx.setStorageSync('user_token', res.result.user_token)
					wx.setStorageSync('phone', res.result.phone)
					wx.showToast({
						title: '登录成功',
						icon: 'none'
					})
	
				})
			},
			fail: function(obj) {}
		})
	},





	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function() {
		
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {
		
	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {
		 this.setData({
		      isBack:app.globalData.isFrom1,
		      cardList:[]
		    })
		 wx.showLoading({
		      title:'加载中',
		      mark:true
		    })
		if(app.globalData.store_id){
			this.setData({
				store_id:app.globalData.store_id,
				type:app.globalData.type_c,
				page:1,
				isNext:true
			},()=>{
				this.getShopList()
			})
		}else{
			this.setData({
				page:1,
				isNext:true
			},()=>{
				this.getShopList()
			})
		}
		
		this.setData({
			isPaying:true
		})
		this.setData({
			step: (567 / 3).toFixed(2)
		})

		this.getTabbarHeight()

		getApp().globalData.type = -1 //重置
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {
		
	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {
		
	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	}
})
